# -*- coding: utf-8 -*-
import hashlib
import web
import random
import time
import ztk_update
import sms
import reply
import receive
import weiyi
import linksql
import json
import sys
import banwords
import weixin
import logging

logger = logging.getLogger()

class Handle(object):
    def GET(self): # 此为微信公众号认证
        webinput = web.input()
        if len(webinput) == 0:
            return 'hello, this is handle view'
        signature = webinput.signature
        timestamp = webinput.timestamp
        nonce = webinput.nonce
        echostr = webinput.echostr
        token = 'test' # 和公众号上设置的一致
        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        list(map(sha1.update, list))
        hashcode = sha1.hexdigest()
        if hashcode == signature:
            return echostr
        else:
            return None
   
    def POST(self):
        try:
            webData = web.data()
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                openid = recMsg.FromUserName #openid
                recContent = recMsg.Content
                linksql.getpid(openid) #分配pid 此处应省略，然后在各处添加要求绑定渠道的信息 此处暂时无法删除是因为非渠道模式需要主动分配pid来临时识别用户。除非强制要求用户绑定渠道，而且必须每月下一单。这个比较困难。
                linksql.updateUser(openid)#每次查询更新用户的信息表
                userText = linksql.sqltbk(openid)#获取用户信息
                if recContent =='提现':
                    return tixian(userText, openid, toUser, fromUser)
                elif recContent == '会员备案':
                    if not(linksql.publisher(openid)):
                        logger.info(openid + ' 会员备案')
                        webdata = weiyi.publishertkl(openid)
                        if webdata['error'] == '0':
                            content = '复制本淘口令打开手机淘宝进行会员备案\n%s\n\n提示:成功备案第二天即可使用机器人哦！'%(webdata['tbk_pwd'])
                        else:
                             content = '淘口令生成失败请联系客服'
                    else:
                        content = '你已经备案了,无需重复备案。'
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                elif recContent == '邀请码':
                    logger.info(openid + ' 邀请码')
                    qrcodeurl = weixin.getqrcode(openid)
                    content = '<a href="%s">点击这里查看你的专属邀请码</a>\n'%(qrcodeurl)
                    content = content + '通过该邀请码关注公众号的均为你的代理，你可以获得他的18%返利，赶紧推荐给更多人吧！'
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                elif recContent == '查询':
                    return userinfo(userText, toUser, fromUser)
                elif len(recContent) == 28 and openid == 'o1mDH1HT8Nf7EdDc2-WJbw8mXkvk':#管理
                    linksql.updateUser(recContent)
                    aduser = linksql.sqltbk(recContent)
                    return userinfo(aduser, toUser, fromUser)
                elif recContent == '帮助':
                    content = '———系统提示———\n'\
                              '发送“签到”每天领取小额红包\n'\
                              '发送“查询”可以查询个人信息\n'\
                              '发送“提现”可以提取当前余额\n'\
                              '发送“帮助”可以查看相关指令\n'\
                              '如有其它问题请加客服微信解决\n'
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                elif recContent == '签到':
                    return qiandao(userText, toUser, fromUser)
                elif recContent == 'openid':
                    content = openid
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                elif recContent == 'appid':
                    content = fromUser
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                elif recContent.isdigit() and len(recContent) == 18:#淘宝订单号
                    sqlorder = linksql.getorder(openid,recContent)
                    if openid == "o1mDH1HT8Nf7EdDc2-WJbw8mXkvk": sqlorder = linksql.getOrderPlus(recContent)
                    if sqlorder:
                       weixin.orderInfo(openid, sqlorder, userText.level_coefficient)
                       logger.info(openid + ' 订单查询成功')
                       return 'success'
                    else:
                        content = '订单查询失败';
                        logger.info(openid + ' 订单查询失败' + recContent)
                        replyMsg = reply.TextMsg(toUser, fromUser, content)
                        return replyMsg.send()
                elif len(recContent) == 19 and recContent.find('2019') > -1:#考虑为时间字符串
                    start_time = recContent
                    tk_orders = ztk_update.getTwentyOrders(start_time,2)
                    if tk_orders:#获得了订单
                        linksql.OrderDetailsAdd(tk_orders)
                        content = '正在收录'
                    else:
                        content = '该时间无订单'
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    logger.info(start_time + ' 申请重新收录')
                    return replyMsg.send()
                else:
                    if linksql.publisher(openid):
                        mmpid = 'mm_32003052_325200030_101473650037' # rid模式通用pid
                        relation_id = linksql.publisher(openid)
                        webdata = weiyi.hcapi(recContent, mmpid, relation_id)
                    elif linksql.openidpid(openid): # pid模式
                        mmpid = 'mm_32003052_324300396_' + str(linksql.openidpid(openid))
                        webdata = weiyi.hcapi(recContent, mmpid)
                    else: # 关系不存在，可能是pid关系库满了，也可能是bug
                        mmpid = 'mm_32003052_315950138_85967650050' # 此为维易默认pid
                        webdata = weiyi.hcapi(recContent, mmpid)
                    logger.info(openid + ' 查询返利')
                    if webdata.result == 1: #有优惠券
                        towords = webdata.tbk_pwd.replace('￥','')
                        index_jian = webdata.coupon_info.find('减')
                        index_yuan = webdata.coupon_info.find('元',index_jian)
                        quan = str(webdata.coupon_info[index_jian + 1 : index_yuan])#优惠券额度
                        title =  banwords.nobantext(webdata.title)
                        replyMsg = reply.NewsMsg(toUser, fromUser, '约返:' + str(round(float(webdata.commission_rate) * 0.01 * userText.level_coefficient * (float(webdata.zk_final_price) - float(quan)),2)) + ' 优惠券:' + quan + ' 付费价:' + str(float(webdata.zk_final_price) - float(quan)), title, webdata.pict_url, 'https://app.budeniao.net/pwd/index.html?taowords=' + towords + '&url=' + webdata.coupon_short_url + '&image=' + webdata.pict_url)
                        return replyMsg.send()
                    elif webdata.result == 2: #无优惠券
                        towords = webdata.tbk_pwd.replace('￥','')
                        title =  banwords.nobantext(webdata.title)
                        replyMsg = reply.NewsMsg(toUser, fromUser, '约返:' + str(round(float(webdata.commission_rate) * 0.01 * userText.level_coefficient * float(webdata.zk_final_price),2)) + ' 优惠券:0' + ' 付费价:' + webdata.zk_final_price, title, webdata.pict_url, 'https://app.budeniao.net/pwd/index.html?taowords=' + towords + '&url=' + webdata.coupon_short_url + '&image=' + webdata.pict_url)
                        return replyMsg.send()
                    elif webdata.result == 3: #商品未加入淘宝客或已经下架
                        content = '———系统消息———\n' + webdata.msg
                        replyMsg = reply.TextMsg(toUser, fromUser, content)
                        return replyMsg.send()
                    else: #非产品ID、或淘口令，或淘客链接
                        content = '———系统消息———\n' + webdata.msg
                        replyMsg = reply.TextMsg(toUser, fromUser, content)
                        return replyMsg.send()
            elif isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'event':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                openid = recMsg.FromUserName
                recEvent = recMsg.Event
                if recEvent == 'subscribe': #关注公众号
                    userText = linksql.sqltbk(openid)
                    EventKey = recMsg.EventKey
                    if EventKey:#有参数
                        scene = EventKey.split('_')
                        proxy = scene[1] #s设置代理
                        if linksql.setProxy(openid, proxy):
                            weixin.customTextSend(openid, '邀请成功！')
                            logger.info(openid + ' 设置代理')
                        else:
                            weixin.customTextSend(openid, '你已经是代理会员了哦！')
                    text = '欢迎关注不得鸟优惠券。\n 你可以点击下方菜单使用教程了解更多哦！'
                    webdata = weiyi.publishertkl(openid)
                    content = '首次使用需绑定淘宝哦！\n请复制这段文字后打开手机淘宝进行绑定。\n' + webdata['tbk_pwd'] 
                    weixin.customTextSend(openid, text) #这个是欢迎信息
                    replyMsg = reply.TextMsg(toUser, fromUser, content) #发送淘宝绑定信息
                    return replyMsg.send()
                elif recEvent == 'CLICK': 
                    recEventKey = recMsg.EventKey
                    linksql.updateUser(openid)#每次查询更新用户的信息表
                    userText = linksql.sqltbk(openid)#获取用户信息              
                    if recEventKey == 'V1001_QIANDAO':#签到
                        return qiandao(userText, toUser, fromUser)
                    elif recEventKey == 'V1001_YAOQING':#邀请码
                        logger.info(openid + ' 邀请码')
                        qrcodeurl = weixin.getqrcode(openid)
                        content = '<a href = "%s">点击你的专属邀请码</a>\n'%(qrcodeurl)
                        content = content +  '邀请码好友关注公众号，你可以获得他的18%返利，赶紧分享给更多人吧!'
                        replyMsg = reply.TextMsg(toUser, fromUser, content)
                        return replyMsg.send()

                    elif recEventKey == 'V1001_JIAOCHENG': #教程
                        title = '省钱购物，必看教程'
                        description = '第一步：点击标题后面的“分享有奖”'
                        picUrl = 'https://app.budeniao.net/logo.jpg'
                        url = 'http://t.cn/EIfL66p'
                        logger.info(openid + " 查看教程")
                        replyMsg = reply.NewsMsg(toUser, fromUser, title, description, picUrl, url) 
                        return replyMsg.send()
                    elif recEventKey == 'V1001_USER': #用户中心
                        return userinfo(userText, toUser, fromUser)
                    elif recEventKey == 'V1001_TIXIAN':#提现申请
                        return tixian(userText, openid, toUser, fromUser)
                    elif recEventKey == 'V1001_KEFU':
                        logger.info(openid + " 联系客服")
                        content = '微信号：13590060134'
                        replyMsg = reply.TextMsg(toUser, fromUser, content)
                        return replyMsg.send()
                elif recEvent == 'SCAN':
                    content = '请分享给其他人关注哦！'
                    return reply.TextMsg(toUser, fromUser, content).send()
                else:
                    logger.warning(openid + ' 该事件未处理：' + recEvent)
                    return 'success'
            else: #非文本消息
                return "success"
        except :
            return None

def qiandao(user, toUser, fromUser):
    lastdate = user.lastdate
    nowdate = time.strftime('%Y-%m-%d', time.localtime())
    if lastdate == nowdate:
        content = '你今天已经签到了'
    else:
        qian = float(random.random()) * 0.12
        logger.info(user.openid + ' 签到：' + str(round(qian,2)))
        linksql.qiandao(user.openid, qian)
        content = '———签到成功———\n' \
                  '【签到额度随机，非固定】\n'  \
                  '本次签到获得%s元\n'  \
                  '可提现金额：%s元\n'  \
                  '———————————\n'  \
                  '发淘宝商品链接给我赚返利！[红包][红包]\n'  \
                  '如有疑问请回复【帮助】查询'%(str(round(qian,2)),str(round(user.remain + qian,2)))
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()

def userinfo(user, toUser, fromUser):
    logger.info(user.openid + ' 查询账户')
    content = '———个人帐户———\n'
    content = content + '已提现金额：%s元\n'%(str(round(user.cashed,2)))
    content = content + '可提现余额：%s元\n'%(str(round(user.remain,2)))
    content = content + '未收货金额：%s元\n'%(str(round(user.goods,2)))
    content = content + '总订单数：%s单\n\n'%(str(user.orders))
    content = content + '提现中：%s元\n'%(str(round(user.cash,2)))
    if int(user.num) > 0:
        content = content + '代理数：%d位\n'%(int(user.num))
        content = content + "推荐奖励：%s元\n"%(round(user.proxy_money,2))
        content = content + "推荐奖励尚在测试中，暂时不能提现。\n"
    content = content + '\n提示：大于5元即可提现如需提现，请回复“提现”\n'
    content = content + '[玫瑰]不要忘记置顶我哦！'
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()

def tixian(user, openid, toUser, fromUser):
    if user.remain < 5:
        content = '———申请失败———\n你现在余额:' + str(round(user.remain,2)) + '元尚不能提现\n\n'
        content = content + '亲，可以发送“查询”两个字，查询账户'
        logger.warning(openid + ' 余额不足提现')
        return reply.TextMsg(toUser, fromUser, content).send()
    if user.cash > 0:#避免重复提现
        content = '你还有一笔提现等待系统完成。'
        logger.warning(openid + ' 重复提现')
        return reply.TextMsg(toUser, fromUser, content).send()
    if not(linksql.checkalipay(openid)):
        content = '第一次提现请绑定支付宝收款账号。\n<a href="http://app.budeniao.net/?openid=%s">点击这里绑定支付宝收款账号。</a>'%(openid)
        logger.warning(openid + ' 支付宝未绑定')
        return reply.TextMsg(toUser, fromUser, content).send()
    if not(linksql.checktixian(openid)):
        content = '下单获得的红包不足5元，暂时无法提现。\n记得多用不得鸟下单哦！'
        logger.warning(openid + ' 不符合提现条件')
        return reply.TextMsg(toUser, fromUser, content).send()
    m = sms.smsTiXian(openid[9:], str(round(user.remain, 2)), user.alipay, user.xingming)
    jsData = json.loads(m)
    if jsData['Message'] == 'OK':
        logger.info(openid + ' 申请提现成功')
        linksql.tixian(openid)
        content = '———申请成功———\n'
        content = content + '本次提现%s元\n系统将会把钱发送到你的支付宝中\n\n24小时内到账'%(str(round(user.remain, 2)))
        content = content + '亲，可以发送“查询”两个字，查询账户'
    else:
        logger.error(openid + ' 提现短信发送失败' + jsData['Message'])
    replyMsg = reply.TextMsg(toUser, fromUser, content)
    return replyMsg.send()
